<script setup lang="ts">
// 引入vue相关
import {nextTick, onMounted, reactive, ref, Ref} from "vue";
// 引入element-plus组件
import {ElMessage, FormInstance} from "element-plus";
// 引入自定义弹框组件
import SysDialog from "@/components/dialog/SysDialog.vue";
// 引入弹框组件的Hooks封装属性和方法
import useDialog from "@/hooks/useDialog.ts";
// 弹框属性和方法
const {dialog, onShow, onClose, onConfirm} = useDialog()
// 获取全局实例
import useInstance from "@/hooks/useInstance.ts";
// 获取全局 global
const {global} = useInstance()

// 项目api
import {getProjectDocumentListApi} from "@/api/project";
import {ProjectDocument, ProjectDocumentListParam} from "@/api/project/type";

// 电控核价api
import {costPlanListParam} from '@/api/costPricingPlan/type.ts'
import {queryCostPlanListApi,deleteApi,updateStatusApi} from '@/api/costPricingPlan/index.ts'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue";

// 引入Plus图标
import { Plus } from '@element-plus/icons-vue';
// 引入vue-router
import { useRouter } from 'vue-router'
// 获取路由实例
const router = useRouter()

// 定义表单ref实例
const form = ref<FormInstance>()

//定义表单校验规则
const rules = {
}

// 表格数据和总条数和表格高度和加载效果
const dataList = ref<any[]>([])  // 表格列表数据
const total = ref(0)  // 分页器总条数
const loading = ref(false)    // 表格加载效果
const tableHeight = ref(0)    // 表格内容高度

// 定义搜索表单数据
const searchForm = ref<costPlanListParam>({
  projectId: undefined,
  activate: undefined,
  page: 1,
  limit: 10,
})


// 项目选择器相关数据
const projectSelectorVisible = ref(false);
const selectedProject = ref<ProjectDocument | null>(null);


// 项目状态映射
const statusOptions = [
  {value: 0, label: '进行中'},
  {value: 1, label: '已完成'},
  {value: 2, label: '已暂停'},
  {value: 3, label: '已取消'}
];

// 项目选择器搜索字段配置
const projectSearchFields = [
  {label: '项目名称', prop: 'name', type: 'input' as const},
  {label: '项目编号', prop: 'code', type: 'input' as const},
  {label: '客户名称', prop: 'customer', type: 'input' as const},
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions
  }
];

// 项目选择器表格列配置
const projectTableColumns = [
  {prop: 'name', label: '项目名称', width: 250},
  {prop: 'code', label: '项目编号', width: 250},
  {prop: 'customer', label: '客户名称', width: 250},
  {prop: 'manager', label: '项目经理', width: 200}
];



// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    };

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams);
  } catch (error) {
    console.error('获取项目列表失败:', error);
    return {data: {list: [], total: 0}};
  }
};


// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project;
  console.log('选择的项目:', project);
  searchForm.value.projectId = project.id || 0;
};

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true;
};


// 获取数据列表方法
const getDataList = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const res = await queryCostPlanListApi(searchForm.value)
    dataList.value = res.data.list
    total.value = res.data.total
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  searchForm.value.page = 1
  getDataList()
}

// 搜索重置方法
const handleReset = () => {
  searchForm.value = {
    projectId: undefined,
    activate: undefined,
    page: 1,
    limit: 10
  }
  selectedProject.value = null
  getDataList()
}

// 修改核价单的状态
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 激活 作废
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return
  
  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({ id, activate: val ? 1 : 0 })
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}


// 分页变化
const handleCurrentChange = (page: number) => {
  searchForm.value.page = page
  getDataList()
}


// 每页条数变化
const handleSizeChange = (size: number) => {
  searchForm.value.limit = size
  searchForm.value.page = 1
  getDataList()
}


// 删除数据方法
const handleDelete = async (id: number) => {
  try {
    await global.$myConfirm('确定要删除该核价单吗，是否继续?')
    await deleteApi(id)
    ElMessage.success('删除成功')
    getDataList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化金额
const formatPrice = (price: number) => {
  return price ? `¥ ${price.toFixed(2)}` : '¥ 0.00'
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'primary' // 进行中
    case 1: return 'success' // 已完成
    case 2: return 'warning' // 已暂停
    case 3: return 'danger'  // 已取消
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : '-'
}

// 编辑
const handleEdit=(id:number)=>{
  router.push(`/costForm/${id}`)
}

// 新增
const handleAdd=(id:number)=>{
  router.push(`/costForm`)
}

// 页面加载时获取列表数据
onMounted(() => {
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 获取数据列表
  getDataList()
})
</script>

<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card"
             shadow="never">
      <div class="search-wrapper">
        <el-form :inline="true"
                 class="demo-form-inline">
          <el-form-item label="项目信息" required>
            <el-input
                :model-value="selectedProject ? selectedProject.name : ''"
                placeholder="请选择项目"
                readonly
                class="selector-input"
            >
              <template #append>
                <el-button @click="openProjectSelector">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.activate"
                       placeholder="是否生效"
                       clearable
                       style="width: 110px">
              <el-option label="生效" :value="1" />
              <el-option label="作废" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       icon="Search"
                       @click="handleSearch">
              查询
            </el-button>
            <el-button icon="RefreshLeft"
                       @click="handleReset">重置
            </el-button>
          </el-form-item>
          <!-- 添加按钮 -->
          <el-form-item>
            <el-button type="primary" icon="Plus" @click="handleAdd">新增电控核价单
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card"
             shadow="never">
      <el-table :data="dataList"
                :height="tableHeight"
                v-loading="loading"
                element-loading-text="加载中..."
                element-loading-background="rgba(255, 255, 255, 0.7)"
                style="width: 100%"
                stripe
                border>
        <el-table-column type="index" label="序号" min-width="60" align="center" show-overflow-tooltip />
        <el-table-column prop="projectName" label="项目名称" min-width="180" align="center" show-overflow-tooltip />

        <el-table-column prop="totalPrice" label="总价"  min-width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.totalPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
            <el-switch v-model="scope.row.activate"
                       class="ml-2"
                       inline-prompt
                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                       active-text="生效"
                       inactive-text="作废"
                       :active-value="1"
                       :inactive-value="0"
                       @change="activateChange($event === 1,scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页器-->
      <div class="pagination">
        <el-pagination v-model:current-page="searchForm.page"
                       v-model:page-size="searchForm.limit"
                       :page-sizes="[5, 10, 20, 25]"
                       :background="true"
                       layout="prev, pager, next, jumper,->,sizes,total"
                       :total="total"
                       @current-change="handleCurrentChange"
                       @size-change="handleSizeChange" />
      </div>
    </el-card>

  </div>

  <!-- 项目选择器组件 -->
  <ArchiveSelector v-model="projectSelectorVisible"
                   title="选择项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleProjectSelect" />
</template>

<style scoped lang="scss">
.container {
  padding: 20px 20px 0px;

  /*顶部搜索卡片*/
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;
    }

    /*搜索表单*/
    .search-wrapper {
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .separator {
            margin: 0 5px;
            color: #909399;
          }
        }

        .el-input,
        .el-select {
          width: 220px;
        }
      }
    }
  }

  /*数据表格卡片*/
  .list-card {
    :deep(.el-card__body) {
      padding: 15px 20px 5px;
    }

    /*表格样式*/
    :deep(.el-table) {
      // 可扩展表格插槽列自定义样式
    }
  }

  // 分页器
  .pagination {
    margin-top: 5px;
  }

  /* 新增按钮样式 */
  .action-bar {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
